using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class WinView : MonoBehaviour
{
    [SerializeField] private WinBarSystem winBarPrefab;
    private List<WinBarSystem> bar = new List<WinBarSystem>();
    public Transform root;

    /// <summary>
    /// 初始化窗口数据
    /// </summary>
    public void Setup(List<List<BagItemData>> datas)
    {
        ClearBars(); // 先清理已有 bar

        for (int i = 0; i < datas.Count; i++)
        {
            WinBarSystem newBar = Instantiate(winBarPrefab, root);
            newBar.transform.localPosition = new Vector3(0, -1 * i, 0);
            newBar.Setup(datas[i]);
            newBar.OnClosed += HandleBarClosed; // 订阅关闭事件
            bar.Add(newBar);
        }
    }

    /// <summary>
    /// 某个 WinBar 关闭后的回调
    /// </summary>
    private void HandleBarClosed(WinBarSystem closedBar)
    {
        bar.Remove(closedBar); // 从列表移除
        if (bar.Count == 0)
        {
            Destroy(this.gameObject); // 所有 bar 关闭后销毁 WinView
            InfoSystem.Instance.SaveGame();
            SceneManager.LoadScene("MapScene");
        }
    }

    /// <summary>
    /// 清理所有 bar
    /// </summary>
    private void ClearBars()
    {
        foreach (var b in bar)
        {
            if (b != null)
                Destroy(b.gameObject);
        }
        bar.Clear();
    }
}
